package com.geor.scan.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.geor.scan.ImgScanProxy;
import com.geor.scan.R;
import com.geor.scan.core.camera.CameraManager;
import com.geor.scan.core.decoding.CaptureActivityHandler;
import com.geor.scan.core.view.ViewfinderView;
import com.geor.scan.interfaces.ImageParser;
import com.geor.scan.interfaces.Recognizer;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;

import java.io.IOException;


/**
 * Initial the camera
 *
 * @author Ryan.Tang
 * @modify by zhengrui
 */
public class CaptureActivity extends AppCompatActivity implements Callback {
    private SurfaceView mSurfaceView;
    private ImageView mBackImageView;
    private RelativeLayout mLayoutTitle;
    private TextView mTitleTextView;
    private CaptureActivityHandler handler;
    private ViewfinderView viewfinderView;
    private boolean hasSurface;
    private boolean localGalleryQRdecodeFinished = true;
    /**
     * 手机的屏幕密度
     */
    private static float density;
    private static Recognizer recognizer;
    private static ImageParser imageParser;
    private static int type;

    public static int getType() {
        return type;
    }
    public static Recognizer getRecognizer() {
        return recognizer;
    }

    public static ImageParser getImageParser() {
        return imageParser;
    }

    /**
     * Called when the activity is first created.
     */
    public static void launch(Context context, ImageParser imageParser, Recognizer recognizer, int type) {
        Intent intent = new Intent(context, CaptureActivity.class);
        context.startActivity(intent);
        CaptureActivity.imageParser = imageParser;
        CaptureActivity.recognizer = recognizer;
        CaptureActivity.type = type;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_capture);

        initView();
    }

    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            super.onManagerConnected(status);
            switch (status) {
                case BaseLoaderCallback.SUCCESS:
                    break;
                default:
                    super.onManagerConnected(status);
                    break;
            }
        }
    };


    private void initView() {

        density = this.getResources().getDisplayMetrics().density;

        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);

        mLayoutTitle = (RelativeLayout) findViewById(R.id.layout_title);
        mLayoutTitle.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, (int) (ImgScanProxy.getInstance().getTitleHeight() * density)));

        mTitleTextView = (TextView) findViewById(R.id.capture_title_txv);

        mTitleTextView.setText(ImgScanProxy.getInstance().getTitleText(this.getResources()));
        mTitleTextView.setTextSize(ImgScanProxy.getInstance().getTitleTextSize());
        mTitleTextView.setTextColor(ImgScanProxy.getInstance().getTitleTextColor(this.getResources()));

        mSurfaceView = (SurfaceView) findViewById(R.id.preview_view);
        mBackImageView = (ImageView) findViewById(R.id.capture_back_btn);
        mBackImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        CameraManager.init(getApplication());

        hasSurface = false;
    }

    public void setTitleName(String title) {
        mTitleTextView.setText(title);
    }

    private void setCapture() {
        mSurfaceView.setBackgroundColor(0xff000000);
        mSurfaceView.setVisibility(View.VISIBLE);
        mSurfaceView.setBackgroundColor(getResources().getColor(android.R.color.transparent));
    }


    /**
     * 初始化照相机和surfaceView，不断尝试从摄像头获取照片并解码
     * 本方法在Activity的onResume中，以及在扫描功能被关闭后需要再次开启时调用
     */
    private void initScanCamera() {
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
    }

    /**
     * 停止对摄像头的调用以及解码工作
     */
    private void closeCamera() {
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        CameraManager.get().closeDriver();
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (localGalleryQRdecodeFinished) {
            initScanCamera();
        }

        setCapture();

        if (!OpenCVLoader.initDebug()) {
            OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_10, this, mLoaderCallback);
        } else {
            mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        closeCamera();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 处理扫描成功后的方法
     *
     * @param result
     */
    public void handleDecode(Object result) {
        initScanCamera();
        if (result != null) {
            ImgScanProxy.getInstance().getCallBack().OnReceiveDecodeResult(CaptureActivity.this, result);
        } else {
            ImgScanProxy.getInstance().getCallBack().OnReceiveDecodeResult(CaptureActivity.this, "");
        }

    }


    /**
     * 初始化摄像头
     *
     * @param surfaceHolder
     */
    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            CameraManager.get().openDriver(surfaceHolder);
        } catch (IOException ioe) {
            ioe.printStackTrace();

            return;
        } catch (RuntimeException e) {
            e.printStackTrace();
            return;
        }

        if (handler == null) {
            handler = new CaptureActivityHandler(this);
        }
    }

    /**
     * 重新启动扫描
     */
    public void restartCamera() {
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        initCamera(surfaceHolder);
        if (handler != null) {
            handler.restartPreviewAndDecode(CaptureActivity.getType());
        }
    }

    /**
     * 返回按键
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        restartCamera();
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;

    }

    public Handler getHandler() {
        return handler;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();

    }

}